import { Button, Form, Message, Notification } from '@arco-design/web-react';
import React, { useCallback, useEffect, useRef, useState } from 'react';
import { useRecoilValue } from 'recoil';
import { getConversationList } from '../../../../api/conversation';
import { setTicketStaff } from '../../../../api/ticket';
import { getAllStaff } from '../../../../api/utils';
import { ConversationList } from '../../../../common/components/ConversationList';
import { CommonOptionsType, FormSelect } from '../../../../common/components/FormSelect';
import { ConversationInfoItem, ConversationType, PermissionType, UserInfo } from '../../../../common/types/conversation';
import { useManagerIm } from '../../../../hooks/useManagerIm';
import { userInfoState } from '../../../../store/userInfo';
import { ConfigForm, ConversationConfigForm } from './components/ConfigForm';

import './index.css'

const FormItem = Form.Item;
interface TicketConfigProps {
  currentConversation?: ConversationInfoItem;
  handleChangeConversation: (conversation: ConversationInfoItem) => void;
}



export const TicketConfig = (props: TicketConfigProps) => {
  const { currentConversation, handleChangeConversation } = props;

  const [conversationInfo, setConversationInfo] = useState<Array<ConversationInfoItem>>([]);
  const [selectOptions, setSelectOptions] = useState<Array<CommonOptionsType>>([]);

  const conversationRef = useRef<any>(currentConversation);
  const managerIm = useManagerIm();
  const userInfo = useRecoilValue(userInfoState);

  const initConversationInfo = useCallback(async (conversation?: ConversationInfoItem) => {
    const result = await getConversationList();
    const { data } = result;
    const { conversation_list } = data;
    const my_conversation_list = conversation_list.filter((item: any) => {
      return item.type !== ConversationType.End
    })
    my_conversation_list && setConversationInfo(my_conversation_list);
    my_conversation_list && handleChangeConversation(conversation || my_conversation_list[0]);
  }, [currentConversation]);

  const handleSubmit = useCallback(async (values: ConversationConfigForm) => {
    const { staffId } = values;
    if (values.staffId === currentConversation?.staff_id) {
      Message.warning('工单设置的客服与原来的一致');
      return;
    }

    if (!currentConversation) {
      return;
    }

    const result = await setTicketStaff(staffId, currentConversation.conversation_id);
    const { code, msg, conversation } = result.data;
    if (code === 200) {
      Notification.info({ content: msg })
      await initConversationInfo(conversation);
    }
    console.log(result);
  }, [currentConversation]);

  const initStaffInfos = useCallback(async () => {
    const result = await getAllStaff();
    if (result.data.code === 200) {
      const users = result.data.users
      const options = users.map((item: UserInfo) => {
        return {
          label: item.username,
          value: item.id,
        }
      })
      setSelectOptions(options);
    }
  }, []);

  useEffect(() => {
    initConversationInfo();
    initStaffInfos();
  }, [localStorage.getItem('token')]);

  useEffect(() => {
    conversationRef.current = currentConversation;
  }, [currentConversation])


  useEffect(() => {
    if (userInfo.id) {
      managerIm.on('manager', async (data: { type: number; }) => {
        if (data.type === 1) { // 有新的工单来了，需要更新列表
          if (!(userInfo.permission === PermissionType.customer)) {
            await initConversationInfo(conversationRef.current);
          }
        }
      })

      managerIm.on(`manager_${userInfo.id}`, async (data: any) => {
        const { type, conversation } = data;
        if (type === 2) {
          await initConversationInfo(conversation);
        }
      })
    }

  }, [userInfo]);

  return (<div className='all-conversation-wrapper'>
    {currentConversation ? <>
      <div className='all-conversation-sider'>
        <ConversationList
          currentConversation={currentConversation}
          onlyShowAll={true}
          handleChangeConversation={handleChangeConversation}
          data={conversationInfo} />
      </div>
      <div className='all-conversation-content'>
        <ConfigForm handleSubmit={handleSubmit} currentConversation={currentConversation} selectOptions={selectOptions} />
      </div>
    </> : null}
  </div>)
}